home *** CD-ROM | disk | FTP | other *** search
/ El Mac 9 / El Mac 9.iso / Shareware / Applications / MathPad 2.4 / XFuns / XFun kit / cross src / cross.c next >
Encoding:
C/C++ Source or Header  |  1996-03-26  |  1.9 KB  |  68 lines  |  [TEXT/CWIE]

  1. /* example XFun that processes index values. Computes a 3D cross product
  2.  
  3. MathPad will call the function cross() 3 times to access 3 vector components.
  4. An "array" function must compute its return value based on the index.
  5. MathPad only evaluates the elements that it needs and there are no guarantees
  6. as to which elements will be evaluated or what order they are evaluated in.
  7.  
  8. For computing the cross product, using GetExprMatrix() to get the input vectors
  9. is simple but is not the most efficient technique since it will evaluate all
  10. elements of both vectors on each call.
  11. */
  12.  
  13. #include "callback.h"
  14.  
  15. static short cross(double *retval,funptr callback)
  16. {
  17.    EXPR xpr;
  18.    double *a,*b,i;
  19.    long rows,cols;
  20.    int ok;
  21.    
  22.    if(!GetParmVal(2,&i,callback)) return(FALSE);    /* cross(A,B)[i] index value is parm 2 */
  23.    
  24.    MakeParmExpr(1,&xpr,callback);                    /* vector A is parm 1 */
  25.    ok = GetExprMatrix(xpr,&a,&rows,&cols,callback);
  26.    FreeExpr(xpr,callback);
  27.    if(!ok || rows !=3 || cols !=0)
  28.    {
  29.     if(a) DisposPtr((Ptr)a);
  30.     ErrMsg(" cross(?,) expects 3D vector",NULL,callback);
  31.     return(FALSE);
  32.    }
  33.    
  34.    MakeParmExpr(0,&xpr,callback);                    /* vector B is parm 0 */
  35.    ok = GetExprMatrix(xpr,&b,&rows,&cols,callback);
  36.    FreeExpr(xpr,callback);
  37.    if(!ok || rows !=3 || cols !=0)
  38.    {
  39.     if(a) DisposPtr((Ptr)a);
  40.     if(b) DisposPtr((Ptr)b);
  41.     ErrMsg(" cross(,?) expects 3D vector",NULL,callback);
  42.     return(FALSE);
  43.    }
  44.   
  45.    switch((int)i)            /* calculate component for a given index value */
  46.    {
  47.     case 1: *retval = a[1] * b[2] - a[2] * b[1]; break;
  48.     case 2: *retval = a[2] * b[0] - a[0] * b[2]; break;
  49.     case 3: *retval = a[0] * b[1] - a[1] * b[0]; break;
  50.     default: ok = FALSE;
  51.    }
  52.    
  53.    DisposPtr((Ptr)a);
  54.    DisposPtr((Ptr)b);
  55.    return(ok);
  56. }
  57.  
  58. static short predef(funptr callback)
  59. {
  60.    AddFunDim("cross",3,callback);  /* cross(A,B)[i] = xfun(i,A,B) dim[3] */
  61. }
  62.  
  63. void main(funptr callback)
  64. {
  65.    AddXfun("cross","A,B",&cross,&predef,callback);
  66. }
  67.  
  68.